package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.PrivateApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.news.NoticeNews;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.NewsService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * @author hqb
 */
@Service
public class DefaultNewsService implements NewsService {

    @Autowired
    private PrivateApi privateApi;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private SettingUtils settingUtils;

    @Override
    public NoticeNews findOne(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(privateApi.getPrivateapiBaseURL()).append(PrivateApi.QUERY_ONE_NEWS)
            .append(".json?id={id}&appkey={appkey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("id", String.valueOf(id));
        NoticeNews noticeNews = new NoticeNews();
        String result = privateApi.get(builder.toString(), kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            JSONObject data = jo.getJSONObject("data");
            Gson gson = new GsonBuilder().create();
            noticeNews = gson.fromJson(data.toString(), NoticeNews.class);
            noticeNews.setImage(noticeNews.getImage());
        }
        return noticeNews;
    }

    @Override
    public List<Map<String, Object>> findNews() {
        StringBuilder builder = new StringBuilder();
        builder.append(privateApi.getPrivateapiBaseURL()).append(PrivateApi.QUERY_NEWS)
            .append(".json?appkey={appkey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("page", String.valueOf(1));
        builder.append("&page={page}");
        kv.put("rows", String.valueOf(5));
        builder.append("&rows={rows}");

        String result = privateApi.get(builder.toString(), kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        List<NoticeNews> noticeNews = new ArrayList<NoticeNews>();

        if (code == 0) {
            JSONObject data = jo.getJSONObject("data");
            JSONArray ja = data.getJSONArray("rows");
            Gson gson = new GsonBuilder().create();
            noticeNews = gson.fromJson(ja.toString(), new TypeToken<List<NoticeNews>>() {
            }.getType());
        }

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (!CollectionUtils.isEmpty(noticeNews)) {
            Setting setting = settingUtils.get();
            for (NoticeNews news : noticeNews) {
                Map<String, Object> map = new HashMap<String, Object>();

                map.put("newsId", news.getId());
                map.put("status", news.getStatus());
                map.put("image", news.getImage());

                String customUrl = "";
                if (setting.getWebUrl().endsWith("/")) {
                    customUrl = setting.getWebUrl();
                } else {
                    customUrl = setting.getWebUrl() + "/";
                }

                map.put("url", customUrl + "passenger/api/rest/v4/news/news?id=" + news.getId());
                map.put("title", news.getTitle());
                map.put("author", news.getAuthor());
                map.put("updated", news.getUpdated());
                map.put("serviceType", news.getServiceType());
                map.put("contType", news.getContType());
                map.put("link", news.getLink());
                map.put("companyId", news.getCompanyId());
                map.put("created",
                    com.ybkj.daijia.constant.DateConstant.DATE_TIME.format(news.getCreated() * 1000));

                list.add(map);
            }
        }
        return list;
    }

    @Override
    public Page<Map<String, Object>> queryNews(String companyIds, Long companyId,
        String serviceType, String contType, Integer page, Integer rows) {
        StringBuilder builder = new StringBuilder();
        builder.append(privateApi.getPrivateapiBaseURL()).append(PrivateApi.QUERY_NEWS)
            .append(".json?appkey={appkey}");
        Map<String, String> kv = new HashMap<String, String>();
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (null != serviceType) {
            kv.put("serviceType", String.valueOf(serviceType));
            builder.append("&serviceType={serviceType}");
        }
        if (null != contType) {
            kv.put("contType", String.valueOf(contType));
            builder.append("&contType={contType}");
        }
        if (null != companyId) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        if (null != companyIds) {
            kv.put("companyIds", String.valueOf(companyIds));
            builder.append("&companyIds={companyIds}");
        }

        String result = privateApi.get(builder.toString(), kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        Long total = 0L;
        List<NoticeNews> noticeNews = new ArrayList<NoticeNews>();

        if (code == 0) {
            JSONObject data = jo.getJSONObject("data");
            total = data.getLong("total");
            JSONArray ja = data.getJSONArray("rows");
            Gson gson = new GsonBuilder().create();
            noticeNews = gson.fromJson(ja.toString(), new TypeToken<List<NoticeNews>>() {
            }.getType());
        }

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (!CollectionUtils.isEmpty(noticeNews)) {
            for (NoticeNews news : noticeNews) {
                Map<String, Object> map = new HashMap<String, Object>();

                map.put("id", news.getId());
                map.put("status", news.getStatus());
                map.put("image", news.getImage());
                map.put("title", news.getTitle());
                map.put("author", news.getAuthor());
                map.put("updated", news.getUpdated());
                map.put("serviceType", news.getServiceType());
                map.put("contType", news.getContType());
                map.put("content", news.getContent());
//				String link = news.getLink();
//				if (null != link && !link.isEmpty() && (!link.startsWith("http://") || !link.startsWith("https://"))) {
//					link = "http://" + link;
//				}
                map.put("link", news.getLink());
                Company company = companyService.findOne(news.getCompanyId());
                map.put("company", company);
                map.put("companyId", news.getCompanyId());
                map.put("created",
                    com.ybkj.daijia.constant.DateConstant.DATE_TIME.format(news.getCreated() * 1000));

                list.add(map);
            }
        }

        return new PageImpl<Map<String, Object>>(list, pageable, total);
    }

    @Override
    public Result<NoticeNews> create(NoticeNews noticeNews) {
        Result<NoticeNews> r = new Result<NoticeNews>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("created", String.valueOf(noticeNews.getCreated() / 1000));
        kv.add("title", noticeNews.getTitle());
        kv.add("author", noticeNews.getAuthor());
        kv.add("image", noticeNews.getImage());
        kv.add("content", noticeNews.getContent());
        kv.add("status", String.valueOf(noticeNews.getStatus()));
        kv.add("serviceType", noticeNews.getServiceType());
        kv.add("contType", noticeNews.getContType());
        kv.add("link", noticeNews.getLink());
        kv.add("companyId", String.valueOf(noticeNews.getCompanyId()));

        String result = privateApi
            .postMultiValueMap(privateApi.getPrivateapiBaseURL() + privateApi.SAVE_NEWS, kv,
                settingUtils.get());

        if (null != result) {

            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");

            if (code == 0) {
                r.setSuccess(true);
            } else {
                String message = jo.getString("message");
                r.setMessage(message);
                r.setSuccess(false);
            }
        }
        return r;
    }

    @Override
    public Result<NoticeNews> delete(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(privateApi.getPrivateapiBaseURL()).append(PrivateApi.DELETE_NEWS)
            .append("?id={id}&appkey={appkey}");

        Result<NoticeNews> result = new Result<NoticeNews>();

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(id));
        String delete = privateApi.delete(builder.toString(), kv, settingUtils.get());
        if (StringUtils.isBlank(delete)) {
            result.setSuccess(true);
        } else {
            result.setSuccess(false);
        }

        return result;
    }

    @Override
    public Result<NoticeNews> update(NoticeNews noticeNews) {

        Result<NoticeNews> r = new Result<NoticeNews>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("created", String.valueOf(System.currentTimeMillis() / 1000));
        kv.add("id", String.valueOf(noticeNews.getId()));
        kv.add("status", String.valueOf(noticeNews.getStatus()));
        if (StringUtils.isNotBlank(noticeNews.getContent())) {
            kv.add("content", noticeNews.getContent());
        }
        if (StringUtils.isNotBlank(noticeNews.getAuthor())) {
            kv.add("author", noticeNews.getAuthor());
        }
        if (StringUtils.isNotBlank(noticeNews.getImage())) {
            String image = noticeNews.getImage();
//			if (noticeNews.getImage().contains("http")) {
//				image = "/upload" + noticeNews.getImage().split("upload")[1];
//			}
            kv.add("image", image);
        }
        if (StringUtils.isNotBlank(noticeNews.getTitle())) {
            kv.add("title", noticeNews.getTitle());
        }
        if (StringUtils.isNotBlank(noticeNews.getServiceType())) {
            kv.add("serviceType", noticeNews.getServiceType());
        }
        if (StringUtils.isNotBlank(noticeNews.getContType())) {
            kv.add("contType", noticeNews.getContType());
        }
        if (StringUtils.isNotBlank(noticeNews.getLink())) {
            kv.add("link", noticeNews.getLink());
        }
        if (null != noticeNews.getCompanyId()) {
            kv.add("companyId", String.valueOf(noticeNews.getCompanyId()));
        }

        String result = privateApi
            .postMultiValueMap(privateApi.getPrivateapiBaseURL() + privateApi.UPDATE_NEWS, kv,
                settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");

            if (code == 0) {
                r.setSuccess(true);
            } else {
                String message = jo.getString("message");
                r.setMessage(message);
                r.setSuccess(false);
            }
        }
        return r;

    }
}
